package gui.customizer.panes.dhcp;

import java.awt.event.ActionListener;
import java.util.HashMap;

import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;

import core.models.DhcpClient;

public class ClientEditor extends JPanel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3455659619899429974L;
	private JTextField txtName;
	private JTextField txtMacAddress;
	private JTextField txtIpAddress;
	private JButton btnApplyChanges;

	/**
	 * Create the panel.
	 */
	public ClientEditor() {
		setLayout(new MigLayout("", "[150]15[150]", "[][]20[][]15[]"));
		
		JLabel lblName = new JLabel("Name");
		add(lblName, "cell 0 0");
		
		txtName = new JTextField();
		add(txtName, "cell 0 1,growx");
		txtName.setColumns(10);
		
		JLabel lblMacAddress = new JLabel("MAC Address");
		add(lblMacAddress, "cell 0 2");
		
		JLabel lblIpAddress = new JLabel("IP Address");
		add(lblIpAddress, "cell 1 2");
		
		txtMacAddress = new JTextField();
		add(txtMacAddress, "cell 0 3,growx");
		txtMacAddress.setColumns(10);
		
		txtIpAddress = new JTextField();
		add(txtIpAddress, "cell 1 3,growx");
		txtIpAddress.setColumns(10);
		
		btnApplyChanges = new JButton("Apply Changes");
		add(btnApplyChanges, "cell 0 4");
	}
	
	public void addListenerToApplyButton(ActionListener l) {
		btnApplyChanges.addActionListener(l);
	}
	
	public void setClient(DhcpClient client) {
		HashMap<String, String> options = client.getOptions();
		
		// Name
		txtName.setText(client.getName());
		
		// MAC Address
		if (options.containsKey("hardware")) {
			String[] value = options.get("hardware").split(" ");
			if (value.length == 2 && value[0].equals("ethernet")) {
				txtMacAddress.setText(value[1]);
			} else {
				txtMacAddress.setText("");
			}
		} else {
			txtMacAddress.setText("");
		}
		
		// IP Address
		if (options.containsKey("fixed-address")) {
			txtIpAddress.setText(options.get("fixed-address"));
		} else {
			txtIpAddress.setText("");
		}
		
		btnApplyChanges.setVisible(true);
	}
	
	public DhcpClient getClient() {
		// Name
		DhcpClient client = new DhcpClient(txtName.getText());
		HashMap<String, String> options = client.getOptions();
		
		// MAC Address
		if (!txtMacAddress.getText().equals("")) {
			options.put("hardware", "ethernet " + txtMacAddress.getText());
		}
		
		// IP Address
		if (!txtIpAddress.getText().equals("")) {
			options.put("fixed-address", txtIpAddress.getText());
		}
		
		return client;
	}
	
	public void hideApplyButton() {
		btnApplyChanges.setVisible(false);
	}
	
	public void clearAll() {
		txtName.setText("");
		txtMacAddress.setText("");
		txtIpAddress.setText("");
		btnApplyChanges.setVisible(false);
	}

}
